package org.confucianismframework.orm.sql.produce.support;

import org.confucianismframework.orm.enums.SQLType;
import org.confucianismframework.orm.pattern.EntityNamePattern;
import org.confucianismframework.orm.annotation.RegisterSQLStrategy;
import org.confucianismframework.orm.sql.produce.SqlProduce;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;

/**
 * 生成 Update 语句
 *
 * @author zy
 */
@RegisterSQLStrategy(SQLType.UPDATE)
public class UpdateSqlProduce implements SqlProduce {

    @Override
    public String produce(Object instance) {

        Class<?> instanceClazz = instance.getClass();

        List<Field> fields = Arrays.asList(instanceClazz.getDeclaredFields());

        StringBuilder sql = new StringBuilder(100);

        // UPDATE table_name SET
        sql.append("UPDATE " + EntityNamePattern.humpToLine(instanceClazz.getSimpleName()) + " SET ");

        // UPDATE table_name SET column_1 = ?, column_2 = ?,
        for (Field field : fields) {

            field.setAccessible(true);

            String column = field.getName();

            // SET 中排除 id
            if (column.equals("id")) {
                continue;
            }

            // 驼峰转下划线
            sql.append(EntityNamePattern.humpToLine(column)).append("=").append("?,");
        }

        // UPDATE table_name SET column_1 = ?, column_2 = ? WHERE id = ?
        sql = sql.deleteCharAt(sql.length() - 1);
        sql.append(" WHERE id=?");

        return sql.toString();
    }

}
